package hbase;

import java.io.IOException;
import java.io.InterruptedIOException;

import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.hbase.HBaseConfiguration;
import org.apache.hadoop.hbase.HColumnDescriptor;
import org.apache.hadoop.hbase.HTableDescriptor;
import org.apache.hadoop.hbase.TableName;
import org.apache.hadoop.hbase.client.Get;
import org.apache.hadoop.hbase.client.HBaseAdmin;
import org.apache.hadoop.hbase.client.HTable;
import org.apache.hadoop.hbase.client.Put;
import org.apache.hadoop.hbase.client.Result;
import org.apache.hadoop.hbase.client.ResultScanner;
import org.apache.hadoop.hbase.client.RetriesExhaustedWithDetailsException;

public class demo1 {
	private static final String tableName = "mytab";
	private static final String familyName = "info";
	private static final String rowKey = "yefei2";

	public static void main(String[] args) throws Exception {

		Configuration conf = HBaseConfiguration.create();
		conf.set("hbase.rootdir", "hdfs://s2:8020/hbase");
		// 使用eclipse时必须添加这个，否则无法定位
		conf.set("hbase.zookeeper.quorum", "s2,s60,S5");

		HBaseAdmin hBaseAdmin = new HBaseAdmin(conf);

		// 创建表
		creatTable(hBaseAdmin);

		// 插入数据

		HTable hTable = new HTable(conf, tableName);
		 putData(hTable);

		// get数据

		// getValue(hTable);
		// scan 表数据
		// scanTable(hTable);

		//hBaseAdmin.disableTable(tableName);
		//hBaseAdmin.deleteTable(tableName);

		hTable.close();

	}

	private static void scanTable(HTable hTable) throws IOException {
		ResultScanner scanner = hTable.getScanner(familyName.getBytes());
		for (Result result : scanner) {
			byte[] value = result.getValue(familyName.getBytes(),
					"age".getBytes());
			System.out.println(result + "\t" + new String(value));
		}
	}

	private static void getValue(HTable hTable) throws IOException {
		Get get = new Get(rowKey.getBytes());
		Result result = hTable.get(get);

		byte[] value = result.getValue(familyName.getBytes(), "age".getBytes());
		System.out.println(result + "\t" + new String(value));
	}

	private static void putData(HTable hTable) throws InterruptedIOException,
			RetriesExhaustedWithDetailsException {
		// row keyO
		Put put = new Put(rowKey.getBytes());
		put.add(familyName.getBytes(), "age".getBytes(), "24".getBytes());
		hTable.put(put);
	}

	private static void creatTable(HBaseAdmin hBaseAdmin) throws IOException {

		boolean tableExists = hBaseAdmin.tableExists(tableName);
		if (!tableExists) {
			TableName name = TableName.valueOf(tableName);
			HTableDescriptor desc = new HTableDescriptor(name);
			HColumnDescriptor family = new HColumnDescriptor(familyName);
			desc.addFamily(family);
			hBaseAdmin.createTable(desc);
		}
	}

}
